/************************************************************************
* model.c
* voxelands - 3d voxel world sandbox game
* Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "common.h"
#include "graphics.h"
#include "array.h"
#include "list.h"
#include "crypto.h"

#include <string.h>

static struct {
	model_t *models;
} model_data = {
	NULL
};

/* create a new model */
model_t *model_create()
{
	model_t *m = malloc(sizeof(model_t));
	m->step = NULL;

	m->meshes = array_create(ARRAY_TYPE_PTR);
	m->skeletons = NULL;
	m->name[0] = 0;

	model_data.models = list_push(&model_data.models,m);

	return m;
}

/* destroy a model */
void model_free(model_t *mdl)
{
	if (mdl->meshes) {
		mesh_t *m;
		while ((m = array_pop_ptr(mdl->meshes))) {
			mesh_free(m);
		}
		array_free(mdl->meshes,1);
	}
	/* TODO: free joints properly */
	if (mdl->skeletons)
		array_free(mdl->skeletons,1);

	if (mdl->name)
		free(mdl->name);

	free(mdl);
}

/* find a model */
model_t *model_find(char* name)
{
	model_t *m;
	uint32_t h = hash(name);

	m = model_data.models;
	while (m) {
		if (m->h == h && !strcmp(m->name,name))
			return m;
		m = m->next;
	}


	return NULL;
}

/* load a model from file */
model_t *model_load(char* file, char* name)
{
	file_t *f;
	model_t *o = NULL;

	f = file_load("model",file);
	if (!f) {
		vlprintf(CN_ERROR, "%s: no such file",file);
		return NULL;
	}

/*	if (!strncmp((char*)f->data,"RoseThorn Model",15)) {
		o = model_load_rtm(f);
	}else if (!strncmp((char*)f->data,"MD5Version 10",13)) {
		o = model_load_md5(f);
	}else if (*((short*)f->data) == 0x4D4D) {
		o = model_load_3ds(f);
	}else if (!strncmp((char*)f->data,"MS3D000000",10)) {
		o = model_load_ms3d(f);
	}else */if (strstr((char*)f->data,"\nusemtl ")) {
		o = model_load_obj(f);
	}else{
		vlprintf(CN_ERROR, "unknown model format");
	}

	if (o) {
		if (!name)
			name = f->name;

		strncpy(o->name,name,256);
		o->h = hash(name);
	}

	file_free(f);

	return o;
}
